import sys

from django import http
from django.core import signals
from django.core.handlers import base
from django.core.urlresolvers import set_script_prefix
from django.utils.log import getLogger

logger = getLogger('django.request')

# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
STATUS_CODE_TEXT = {
    100: 'CONTINUE',
    101: 'SWITCHING PROTOCOLS',
    200: 'OK',
    201: 'CREATED',
    202: 'ACCEPTED',
    203: 'NON-AUTHORITATIVE INFORMATION',
    204: 'NO CONTENT',
    205: 'RESET CONTENT',
    206: 'PARTIAL CONTENT',
    300: 'MULTIPLE CHOICES',
    301: 'MOVED PERMANENTLY',
    302: 'FOUND',
    303: 'SEE OTHER',
    304: 'NOT MODIFIED',
    305: 'USE PROXY',
    306: 'RESERVED',
    307: 'TEMPORARY REDIRECT',
    400: 'BAD REQUEST',
    401: 'UNAUTHORIZED',
    402: 'PAYMENT REQUIRED',
    403: 'FORBIDDEN',
    404: 'NOT FOUND',
    405: 'METHOD NOT ALLOWED',
    406: 'NOT ACCEPTABLE',
    407: 'PROXY AUTHENTICATION REQUIRED',
    408: 'REQUEST TIMEOUT',
    409: 'CONFLICT',
    410: 'GONE',
    411: 'LENGTH REQUIRED',
    412: 'PRECONDITION FAILED',
    413: 'REQUEST ENTITY TOO LARGE',
    414: 'REQUEST-URI TOO LONG',
    415: 'UNSUPPORTED MEDIA TYPE',
    416: 'REQUESTED RANGE NOT SATISFIABLE',
    417: 'EXPECTATION FAILED',
    500: 'INTERNAL SERVER ERROR',
    501: 'NOT IMPLEMENTED',
    502: 'BAD GATEWAY',
    503: 'SERVICE UNAVAILABLE',
    504: 'GATEWAY TIMEOUT',
    505: 'HTTP VERSION NOT SUPPORTED',
}

class InvalidZMQObject(Exception):
	"""docstring for InvalidZMQObject"""
	def __init__(self, arg):
		super(InvalidZMQObject, self).__init__()
		self.arg = arg
	#__init__()

	def __repr__(self):
		"""docstring for __repr__"""
		return self.arg
	#__repr__()
#InvalidZMQObject

from djangodmq import ZMQRequest

class ZMQHandler(base.BaseHandler):
	"""docstring for ZMQHandler"""
	request_class = ZMQRequest
		
	def __call__(self, environ, zpo):
		"""
		ZeroMQ Django Handler. This analagous to the WSGI or MOD_PYTHON
		handlers.

		zpo is expected to be a JSON string, fresh of the ZMQ 'wire'
		"""

		from django.conf import settings

		# Set up middleware if needed.
		if self._request_middleware is None:
			try:
				self.load_middleware()
			except:
				# Unload whatever middleware we got
				self._request_middleware = None
				raise

		set_script_prefix(base.get_script_name(environ))
		signals.request_started.send(sender=self.__class__)

		try:
			try:
				request = self.request_class(environ, zpo)
			except UnicodeDecodeError:
				logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
				   exc_info=sys.exc_info(),
				   extra={
						   'status_code': 400,
						   'request': request
						   }
				   )
				response = http.HttpResponseBadRequest()
			else:
				response = self.get_response(request)
		finally:
			signals.request_finished.send(sender=self.__class__)

		try:
			status_text = STATUS_CODE_TEXT[response.status_code]
		except KeyError:
			status_text = 'UNKNOWN STATUS CODE'

		status = '%s %s' % (response.status_code, status_text)
		response_headers = [(str(k), str(v)) for k, v in response.items()]

		for c in response.cookies.values():
			response_headers.append(('Set-Cookie', str(c.output(header=''))))

		#start_response(status, response_headers)

		return response
	#__call__()
#ZMQHandler
